property pcount,pindex
property nextFN,finished
property computedValue
property ProcessAsControlStructure
--property Just,IsNothing

on new me,fn,c,firstParameterIsTheScriptInstance,AsControlStructure
  me.finished = false
  me.pindex = not voidP(firstParameterIsTheScriptInstance)
  me.pcount = c
  
  me.ProcessAsControlStructure = AsControlStructure
  me.SetNextStep(fn)
  
  return me
end

on getValue me
  c = me.computedValue
  
  
  if me.finished then
    me.computedValue = void
  end if
  
  return c
end

on process me,currentElem
  
  Just = LingoF().getLambda(#LingoF, #Just)
  
  if me.finished then return false
  if me.ProcessAsControlStructure then return me.SetNextStep(me.nextFN [ [currentElem] ]  )
  return me.SetNextStep(me.nextFN [Just[currentElem]]  )
end

on SetNextStep me,f
  me.nextFN = f
  if (me.pcount = me.pindex) then    
    finished = true    
    me.computedValue = me.nextFN [ [] ]    
    me.nextFN = void
  else pindex = pindex + 1
  return not finished
end


-- Note: All Lambdas called by 'process' should be tail recursive and to consume a paramater, the parameter should be curried when calling the function.